home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1997 February / EnigmA AMIGA RUN 15 (1997)(G.R. Edizioni)(IT)[!][issue 1997-02][PLANET CD V].iso / progs / sviluppo / python-1.4 / lib / tempfile.py < prev    next >
Text File  |  1996-12-16  |  2KB  |  79 lines

  1. # Temporary file name allocation
  2. #
  3. # XXX This tries to be not UNIX specific, but I don't know beans about
  4. # how to choose a temp directory or filename on MS-DOS or other
  5. # systems so it may have to be changed...
  6.  
  7.  
  8. import os
  9.  
  10.  
  11. # Parameters that the caller may set to override the defaults
  12.  
  13. tempdir = None
  14. template = None
  15.  
  16.  
  17. # Function to calculate the directory to use
  18.  
  19. def gettempdir():
  20.     global tempdir
  21.     if tempdir is not None:
  22.     return tempdir
  23.     attempdirs = ['/usr/tmp', '/tmp', os.getcwd(), os.curdir]
  24.     if os.name == 'nt':
  25.     attempdirs.insert(0, 'C:\\TEMP')
  26.     attempdirs.insert(0, '\\TEMP')
  27.     elif os.name == 'amiga':
  28.     attempdirs.insert(0, 'SYS:T')
  29.     attempdirs.insert(0, ':T')
  30.     attempdirs.insert(0, 'T:')
  31.     if os.environ.has_key('TMPDIR'):
  32.     attempdirs.insert(0, os.environ['TMPDIR'])
  33.     testfile = gettempprefix() + 'test'
  34.     for dir in attempdirs:
  35.     try:
  36.         filename = os.path.join(dir, testfile)
  37.         fp = open(filename, 'w')
  38.         fp.write('blat')
  39.         fp.close()
  40.         os.unlink(filename)
  41.         tempdir = dir
  42.         break
  43.     except IOError:
  44.         pass
  45.     if tempdir is None:
  46.     msg = "Can't find a usable temporary directory amongst " + `attempdirs`
  47.     raise IOError, msg
  48.     return tempdir
  49.  
  50.  
  51. # Function to calculate a prefix of the filename to use
  52.  
  53. def gettempprefix():
  54.     global template
  55.     if template == None:
  56.         if os.name == 'posix' or os.name=='amiga':
  57.             template = '@' + `os.getpid()` + '.'
  58.         else:
  59.             template = 'tmp' # XXX might choose a better one
  60.     return template
  61.  
  62.  
  63. # Counter for generating unique names
  64.  
  65. counter = 0
  66.  
  67.  
  68. # User-callable function to return a unique temporary file name
  69.  
  70. def mktemp():
  71.     global counter
  72.     dir = gettempdir()
  73.     pre = gettempprefix()
  74.     while 1:
  75.         counter = counter + 1
  76.         file = os.path.join(dir, pre + `counter`)
  77.         if not os.path.exists(file):
  78.             return file
  79.